package com.shark.security.jwt.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import com.shark.security.jwt.security.model.JwtUser;

/**
 * 自定义验证
 * @author junxiao
 *
 */
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
	
	@Autowired
	private JwtUserDetailsServiceImpl userDetailService;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		String username = authentication.getName();
		String password = (String)authentication.getCredentials();
		JwtUser userInfo = (JwtUser)userDetailService.loadUserByUsername(username);
		if (userInfo == null) {
            throw new BadCredentialsException("用户不存在");
		}
		if (!userInfo.getPassword().equals(password)) {
			throw new BadCredentialsException("密码不正确");
		}
		return new UsernamePasswordAuthenticationToken(
				userInfo, null, userInfo.getAuthorities());
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return true;
	}

}
